package com.app.service.impl;


import com.alibaba.fastjson.JSON;
import com.app.entity.Binding;
import com.app.entity.User;


import com.app.entity.params.SearchParams;
import com.app.mapper.BindingMapper;
import com.app.mapper.UserMapper;
import com.app.service.QiniuService;
import com.app.service.UserService;
import com.app.util.JwtUtil;
import com.app.util.PageResult;
import com.app.util.Result;
import com.app.util.RoleUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author by zxy on 2021/3/23
 */
@Service
public class UserServiceImpl implements UserDetailsService, UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private BindingMapper bindingMapper;

    @Override
    public UserDetails loadUserByUsername(String tel) throws UsernameNotFoundException {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state", '0');
        queryWrapper.eq("tel", tel);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }


    @Override
    public Result addUserByfront(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("tel", user.getTel());
        User one = userMapper.selectOne(queryWrapper);
        if (one == null) {
            user.setUrl("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
            user.setUsername("无名大咖");
            user.setScore("0");
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            userMapper.insert(user);
            return Result.success();
        }
        return Result.fail("手机号已经存在");
    }

    @Override
    public Result updateUrl(MultipartFile file, Integer id) {
        try {
            String url = qiniuService.uploadFile(file);
            User user = new User();
            user.setUrl(url).setId(id);
            userMapper.updateById(user);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败");
        }
        return Result.success("修改成功");
    }

    @Override
    public Result findUserByid() {
        return Result.success(userMapper.selectById(RoleUtil.getRoleId()));
    }

    @Override
    public Result updateUserByid(User user) {
        userMapper.updateById(user);
        return Result.success("更新成功");
    }

    @Override
    public Result findUserBySearch(SearchParams searchParams) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (searchParams.getManSubject() != null) {
            queryWrapper.eq("man_subject", searchParams.getManSubject());
        }
        if (searchParams.getName() != null) {
            queryWrapper.like("username", searchParams.getName());//用户名
        }
        queryWrapper.eq("rid", searchParams.getRid()); //rid一定要带有
        queryWrapper.orderByDesc("score");
        List list = userMapper.selectList(queryWrapper);
        return Result.success(list);
    }

    @Override
    public Result bindCoach(Integer id) {
        Integer sid = RoleUtil.getRoleId();   //学生id
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state", '0');
        queryWrapper.eq("sid", sid);
        Binding binding = bindingMapper.selectOne(queryWrapper);
        if (binding == null) {
            binding = new Binding();
            binding.setSid(sid).setCid(id);
            bindingMapper.insert(binding);
            return Result.success("关注成功");
        }
        return Result.fail("关注失败，你有关注该科目的教练");
    }

    @Override
    public Result appleText() {
        Integer sid = RoleUtil.getRoleId();
        User user = userMapper.selectById(sid);
        user.setTestState('1');
        userMapper.updateById(user); //申请成功
        bindingMapper.delete(new QueryWrapper<Binding>().eq("sid", sid));//结束绑定
        return Result.success();
    }

    @Override
    public PageResult findUserByAdmin(SearchParams searchParams) {
        Page<User> page = new Page<>(searchParams.getPage(), searchParams.getLimit());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ne("state", '1');//可用
        if (StringUtils.isNotEmpty(searchParams.getName())) {
            queryWrapper.like("username", searchParams.getName());
        }
        if (StringUtils.isNotEmpty(searchParams.getTel())) {
            queryWrapper.like("tel", searchParams.getTel());
        }
        queryWrapper.eq("rid", searchParams.getRid());
        Page pages = userMapper.selectPage(page, queryWrapper); //查询可用用户
        Integer total = userMapper.selectCount(queryWrapper);
        List<User> nopassUser = userMapper.selectList(new QueryWrapper<User>().eq("state", '1').eq("rid", searchParams.getRid()));//新用户申请的
        return PageResult.success(total.longValue(), pages.getRecords()).addmessage("nopass", nopassUser);
    }

    @Override
    public Result findUserPassByAdmin(Integer id) {
        User user = new User().setId(id).setState('0');
        userMapper.updateById(user);
        return Result.success();
    }

    @Override
    public Result findCoachAll() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state",'0');
        queryWrapper.eq("rid",'3');
        return Result.success(userMapper.selectList(queryWrapper));
    }
}
